<?php

namespace Api\Sms\ZhangXin;

use GuzzleHttp\Client;
use Api\Sms\SmsRepository;

class Repository extends SmsRepository
{
    /**
     * 发送短信验证码
     * 
     * @param  string $code        验证码
     * @param  string $countryCode 国际区号
     * @param  string $mobile      手机号码
     * @return array  [$smsStatus, $smsCallbackMessage]
     */
    protected function _sendVerificationCode(string $code, string $countryCode, string $mobile)
    {
        $config = $this->config['mobile'];
        if (preg_match($config['pattern'], $mobile) === 0) {
            $smsStatus = false;
            $smsCallbackMessage = $config['regex'];
            return [$smsStatus, $smsCallbackMessage];
        }
        
        $client = new Client();
        $config = $countryCode === '86' ? $this->config['cn']: $this->config['en'];
        $mobile = $countryCode === '86' ? $mobile: '00'.$countryCode.$mobile;

        // 请求参数
        $url   = $config['api'];
        $query = [
            'action'   => 'send',
            'userid'   => $config['userid'],
            'account'  => $config['account'],
            'password' => $config['password'],
            'mobile'   => $mobile,
            'content'  => str_replace('#code#', $code, $config['tpl']),
        ];
        
        // 发起请求
        $response = $client->request('GET', $url, compact('query'));
        $result   = simplexml_load_string($response->getBody()->getContents());

        // 判断请求结果
        if ($result->returnstatus == 'Success') {
            $smsStatus = true;
            $smsCallbackMessage = $this->config['successMessage'];
        } else {
            $smsStatus = false;
            $smsCallbackMessage = $this->config['failMessage'];
        }

        return [$smsStatus, $smsCallbackMessage];
    }

}
